/**
 * Created by huotaol on 2017/6/22.
 */
import React, {Component} from "react";
import PropTypes from "prop-types";
import {
    Image,
    InteractionManager,
    ScrollView,
    StyleSheet,
    Text,
    TouchableOpacity,
    TouchableWithoutFeedback,
    View
} from "react-native";
import {connect} from "react-redux";
import ModuleCommonHeader from "../../main/module/ModuleCommonHeader";
import InputTextItem from "../../main/record/common/InputTextItem";
import LoadingView from "../../../common/component/LoadingView";
import Util from "../../main/Util";
import SwitchTextItem from "../../main/record/common/SwitchTextItem";
import SingleSelectionTextItem from "../../main/record/common/SingleSelectionTextItem";
import * as RequestUtil from "../../../common/util/RequestUtil";
import Modal from "react-native-modal";
import CustomStyle from "../../../common/style/CustomStyle";
import {Actions} from "react-native-router-flux";
import {setLoadingState} from "../../redux/action/homePage";
import * as Url from "../../constant/Url";

class LoanUI extends Component {
    static propTypes = {
        carInfo: PropTypes.object
    };

    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            loading: true,
            data: {},
            showExpire: false,
            showLoan: false,
            showHouse: false,
            showMarry: true,
            isModalVisible: false,
        };
        this._uploadData = this._uploadData.bind(this);
        this._fetchData = this._fetchData.bind(this);
        this._setDefaultData = this._setDefaultData.bind(this);
    }

    componentDidMount() {
        this._fetchData();
    }

    render() {
        const {data} = this.state;
        return (
            <View style={{flex: 1}}>
                <ModuleCommonHeader title={'我要分期'} clickedRight={() => {
                    this._uploadData(data);
                }} rightText={'提交'}/>
                {this.state.loading ? <LoadingView/> : <ScrollView>
                    <InputTextItem object={data.name}
                                   autoCapitalize='characters'
                    />
                    <InputTextItem object={data.phone}
                                   autoCapitalize='characters'
                    />
                    <SingleSelectionTextItem object={data.expire}
                                             onSelectedListener={value => {
                                                 this.setState({showExpire: value !== '否'});
                                             }}
                                             optionArray={[{name: '否', val: 0},
                                                 {name: '1年内1次逾期', val: 1}, {name: '1年内3次逾期', val: 3}, {
                                                     name: '1年内5次逾期', val: 5
                                                 },]}/>
                    {this.state.showExpire ? <SwitchTextItem object={data.expireExInfo}
                                                             onValueChangedListener={value => {
                                                             }} onValue='是' offValue='否'/> : null}
                    <SwitchTextItem object={data.loan}
                                    onValueChangedListener={value => {
                                        this.setState({showLoan: value});
                                    }} onValue='是' offValue='否'/>
                    {this.state.showLoan ? this._renderSwitch(data.loanList) : null}
                    <SwitchTextItem object={data.hasLoan}
                                    onValueChangedListener={value => {
                                    }} onValue='是' offValue='否'/>
                    <SwitchTextItem object={data.house}
                                    onValueChangedListener={value => {
                                        this.setState({showHouse: value});
                                    }} onValue='是' offValue='否'/>
                    {this.state.showHouse ? this._renderSwitch(data.houseList) : null}
                    <SingleSelectionTextItem object={data.income}
                                             onSelectedListener={value => {

                                             }}
                                             optionArray={[{name: '3000以下',}, {name: '3000-5000',}, {
                                                 name: '5000-8000',
                                             }, {name: '8000-15000',}, {name: '15000-30000',}, {
                                                 name: '30000以上',
                                             }]}/>
                    <SwitchTextItem object={data.marry}
                                    onValueChangedListener={value => {
                                        this.setState({showMarry: !value});
                                    }} onValue='是' offValue='否'/>
                    {this.state.showMarry ? <SwitchTextItem object={data.marryExInfo}
                                                            onValueChangedListener={value => {
                                                            }} onValue='是' offValue='否'/> : null}
                    <InputTextItem object={data.year}
                                   autoCapitalize='characters'
                                   keyboardType={'numeric'}
                    />
                </ScrollView>}
                <TouchableWithoutFeedback onPress={() => {
                    this.setState({isModalVisible: false});
                }}>
                    <Modal isVisible={this.state.isModalVisible}
                           backdropOpacity={0.65}
                    >
                        <LoanTip btClick={() => {
                            this.setState({isModalVisible: false});
                            InteractionManager.runAfterInteractions(() => {
                                Actions.MyEstimate();
                            });
                        }}/>
                    </Modal>
                </TouchableWithoutFeedback>
            </View>
        );
    }

    _fetchData() {

        const {carInfo, userData} = this.props;
        const url = Url.BASE_URL + '/finance/list';
        const param = new FormData();
        param.append('carid', carInfo.carid);
        param.append('userid', userData.id);
        console.log('LoanUI _fetchData  param  ' + JSON.stringify(param));
        RequestUtil.request(url, 'post', param).then(ret => {
            console.log('LoanUI ret    ' + JSON.stringify(ret));
            const {status, list} = ret;
            if (status === 0 && list.length) {
                Util.showToast('已申请过分期');
                Actions.pop();
            } else {
                this._setDefaultData();
            }
        }).catch(err => {
            this._setDefaultData();
        });
    }

    _setDefaultData() {
        const {userData} = this.props;
        const data = Util.loan();
        data.phone.value = userData.phone;
        this.setState({loading: false, data});
    }

    _uploadData(data) {
        const {carInfo, userData} = this.props;
        const url = 'http://192.168.1.122:8080/finance/commit';
        const param = new FormData();
        param.append('carid', carInfo.carid);
        param.append('userid', userData.id);
        param.append('clientname', data.name.value);
        param.append('clientphone', data.phone.value);
        let count = 0;
        if (data.expire.value !== '否') {
            const re = /内(\d)次/;
            count = parseInt(re.exec(data.expire.value)[1]);
            param.append('has_overdue_now', data.expireExInfo.value === '否' ? 0 : 1);
        }
        param.append('overdue_count_per_year', count);
        if (data.loan.value === '是') {
            param.append('loan_type', this._processList(data.loanList));
        }
        param.append('has_loan_or_credit_card', data.hasLoan === '否' ? 0 : 1);
        if (data.house.value === '是') {
            param.append('hpoc_type', this._processList(data.houseList));
        }
        param.append('got_married', data.marry.value === '否' ? 0 : 1);
        if (data.marry.value === '否') {
            param.append('provide_sponsor', data.marryExInfo.value === '否' ? 0 : 1);
        }
        param.append('age', data.year.value);
        param.append('income', data.income.value);
        console.log('LoanUI _uploadData    ' + JSON.stringify(param));
        this.props.setLoading(true, '提交评估材料中');
        RequestUtil.request(url, 'post', param).then(ret => {
            this.props.setLoading(false, '');
            const {status, message} = ret;
            if (status === 0) {
                this.setState({isModalVisible: true});
            } else {
                Util.showToast(message);
            }
            console.log('LoanUI ret    ' + JSON.stringify(ret));
        }).catch(err => {
            this.props.setLoading(false, '');
            Util.showToast(err.message);
        });
    }

    _processList(list, allType = 3) {
        let type = 0;
        let index = 0;
        for (let i = 0; i < list.length; i++) {
            const item = list[i];
            if (item.value === '是') {
                index++;
                type = item.exValue;
            }
        }
        if (index === list.length) {
            type = allType;
        }
        return type;
    }

    _renderSwitch(data) {
        if (Array.isArray(data)) {
            return data.map(item => {
                return <SwitchTextItem object={item}
                                       onValueChangedListener={value => {
                                       }} onValue='是' offValue='否'/>
            });
        }
    }
}


class LoanTip extends Component {
    static propTypes = {
        btClick: PropTypes.func,
    };

    render() {
        return (
            <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
                <Image source={require('../../../img/buyCar/loan_background.png')}
                       resizeMode={'contain'}
                       style={{
                           width: CustomStyle.getActualSizeInHorizontal(500),
                           height: CustomStyle.getActualSizeInVertical(823),
                           justifyContent: 'flex-end',
                           alignItems: 'center',
                           paddingBottom: CustomStyle.getActualSizeInVertical(80),
                       }}>
                    <View style={{
                        alignItems: 'center',
                        width: CustomStyle.getActualSizeInHorizontal(302),
                    }}>
                        <Text style={[CustomStyle.baseText, styles.textNormal]}> 评估结果在 <Text
                            style={[CustomStyle.baseText, styles.textHigh]}>个人中心</Text>
                            查看，评估成功后将<Text style={[CustomStyle.baseText, styles.textHigh]}>发送短信</Text>至您的手机
                        </Text>
                        <TouchableOpacity
                            style={[, {marginTop: CustomStyle.getActualSizeInVertical(32),}]}
                            onPress={this.props.btClick}
                        >
                            <Image source={require('../../../img/buyCar/loan_bt_background.png')}
                                   resizeMode={'contain'}
                                   style={{
                                       width: CustomStyle.getActualSizeInHorizontal(260),
                                       height: CustomStyle.getActualSizeInVertical(78),
                                       alignItems: 'center',
                                       justifyContent: 'center',
                                   }}>
                                <Text style={[CustomStyle.baseText, {
                                    fontSize: CustomStyle.getActualFontSize(30),
                                    color: '#4a3d18',
                                }]}>立即查看</Text>
                            </Image>
                        </TouchableOpacity>
                    </View>

                </Image>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    textNormal: {
        fontSize: CustomStyle.getActualFontSize(24),
        color: '#4a3d18',
    },
    textHigh: {
        fontSize: CustomStyle.getActualFontSize(26),
        color: '#ec5163',
    },
});

const mapStateToProps = (state) => {
    const {userData} = state;
    return {
        userData: userData,
    };
};

const mapDispatchToProps = (dispatch) => {
    return {
        setLoading: (loading, text) => {
            dispatch(setLoadingState(loading, text));
        },
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(LoanUI);